# --------------- < import > ---------------
from chiori import Config, Logger
from .main import VkBackend

import asyncio
import aiohttp
import json
import re
# --------------- < import > ---------------
chat_const = int(2E9)


class VkGroup(VkBackend):
	def __init__(self, app, user=False):
		super(VkGroup, self).__init__()
		self.name = 'vk_backend'
		self.l = Logger('VkBackend')

		self.app = app
		self.user = user
		self.c = Config(self.name, {'token':"token", 'user_token':'user token',
										'group_id':0, 'admins':[],
										'banned':{}, 'banned_chats':[]})
		self.__dict__.update(self.c.group_data)

		self.longpoll = None
		self.longpoll_settings = {}
		self.longpoll = None
		self.longpoll_url = "{}?act=a_check&key={}&wait=25&ts={}"

		if self.user:
			self.api_url = "https://api.vk.com/method/{{}}?access_token={}&v={}" .format(self.user_token, self.version)
		else:
			self.api_url = "https://api.vk.com/method/{{}}?access_token={}&v={}" .format(self.token, self.version)


	async def update_longpoll_data(self):
		"""обновление данных для регистрации на сервере"""
		if self.user:
			method = 'messages.getLongPollServer'
		else:
			method = 'groups.getLongPollServer'

		longpoll = await self.request(method, group_id=self.group_id)
		if not longpoll['error']:
			self.longpoll = {**longpoll['response']}


	async def receiver(self):
		"""получеие обновлений на сервере"""
		try:
			async with aiohttp.ClientSession() as sess:
				async with sess.post(
						self.longpoll_url.format(
							self.longpoll["server"],
							self.longpoll["key"],
							self.longpoll["ts"],
						)
				) as resp:
					response = await resp.json()

		except Exception as e:
			return ()

		if "ts" in response:
			self.longpoll["ts"] = response["ts"]

		if "failed" in response:
			if response["failed"] in (2, 3, 4):
				await self.update_longpoll_data()

			return ()

		updates = []

		for update in response["updates"]:
			if "type" not in update or "object" not in update:
				continue

			updates.append(update)

		return updates

	async def start(self):
		"""запуск logpoll обработчика"""
		await self.app.startEvent()
		if not self.longpoll:
			try:
				await self.update_longpoll_data()
			except Exception as e:
				self.l.log(f"ошибка загрузки: {e}", 'e')
				await self.app.stopEvent()

		# try:
		while True:
			for event in await self.receiver():
				self.l.log(event["type"])
				if event['type'] != 'message_new':
					self.l.log(event['object'], event['type'])
				else:
					event = await self.convert_to_message(event)
					await self.app.messageEvent(event)
			await asyncio.sleep(0.01)
		# except Exception as e:
			# self.l.log(e, 'e')
